import json
import logging
from django.http import JsonResponse
from django.utils.deprecation import MiddlewareMixin
from django.conf import settings

logger = logging.getLogger(__name__)

class AuthMiddleware(MiddlewareMixin):
    """认证中间件"""
    
    def process_request(self, request):
        """请求预处理"""
        # 记录请求信息
        if settings.DEBUG:
            logger.info(f"Request: {request.method} {request.path}")
        
        # 设置默认用户信息
        request.user_info = None
        request.user_id = None
        request.oauth_info = None
        
        return None
    
    def process_response(self, request, response):
        """响应后处理"""
        # 添加安全头
        response['X-Content-Type-Options'] = 'nosniff'
        response['X-Frame-Options'] = 'DENY'
        response['X-XSS-Protection'] = '1; mode=block'
        
        return response
    
    def process_exception(self, request, exception):
        """异常处理"""
        logger.error(f"Request exception: {str(exception)}")
        
        # 根据异常类型返回适当的错误响应
        if isinstance(exception, (ValueError, TypeError)):
            return JsonResponse({
                "code": 400,
                "msg": "请求参数错误",
                "data": None
            }, status=400)
        
        return JsonResponse({
            "code": 500,
            "msg": "服务器内部错误",
            "data": None
        }, status=500)

class CORSMiddleware(MiddlewareMixin):
    """CORS中间件"""
    
    def process_response(self, request, response):
        """添加CORS头"""
        response['Access-Control-Allow-Origin'] = '*'
        response['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS'
        response['Access-Control-Allow-Headers'] = 'Content-Type, Authorization, X-API-Key'
        response['Access-Control-Max-Age'] = '86400'
        
        return response